<template>
	<view class="content" :class="['content-page-' + game.theme]" @tap="palyClickAudio"
	:style="game.bg?'--content-bg:url('+game.bg+');':''">
		<view class="box-line" ref="containerRef" v-show="list.length > 0" :style="containerStyle">
			<view class="item" v-for="(item, index) in list" :key="index" :style="item.style" @tap="setSelected(item)">
				<template v-if="!!item.icon">
					<image :src="item.icon" class="w-100 h-100" />
				</template>
				<template v-else>{{ index + 1 }}</template>
			</view>
			<view class="item" v-for="(role, index) in roles" :key="index" :style="role.style">
				<image :src="role.icon" class="w-100 h-100"  v-if="role.icon"/>
				<text v-else>{{role.nickname}}</text>
			</view>
			<view class="rule-position" v-if="game.rule_content">
				<view class="h8 font-weight-600 text-center mb-4">游戏规则</view>
				<text class="h9 py-1">{{game.rule_content}}</text>
			</view>
			<view class="dice-position">
				<x-dice @finish="diceFinish" />
			</view>
			<view class="btn-position flex grid-gap-4 flex-center">
				<view class="bg-danger text-white rounded-4 px-6 py-2 font-weight-600 text-center h8"
					hover-class="bg-danger-dark-1" @tap="close(true)">结束游戏</view>
				<view class="bg-primary text-white rounded-4 px-6 py-2 font-weight-600 text-center h8"
					hover-class="bg-primary-dark-1" @tap="reset(true)">重来</view>
			</view>
		</view>
		<toggle-sound />
		<x-popup v-model="showPopup" top="70vh" style="--x-popup-bg-image:linear-gradient(180deg, var(--item-bg-1), var(--item-bg-2))">
			<view class="h6 font-weight-600 p-4 text-center rule-color">{{ taskItem.title }}</view>
			<view class="flex-1 flex flex-center px-4">
				<view class="h8 text-center font-weight-600 rule-color">{{ taskItem.content }}</view>
			</view>
		</x-popup>
	</view>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue';
import { onLoad,onUnload } from "@dcloudio/uni-app";
import { $http, $page,useGameCustom,createAudio } from '@/utils';
import { useWebConfigStore,useRefs } from '@/stores';
const webConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(webConfigStore);
const showPopup = ref<boolean>(false);
const containerRef = ref<HTMLElement>();
const containerStyle=ref<any>({
	width: '0px',
	height: '0px'
});
const list = ref<{
	content: string;
	nature_text?: string;
	icon?: string;
	style?: any;
}[]>([]);
const game = ref<any>({
	theme: '',
	bg: '',
	rule_content:"1.每个人轮流掷骰子，根据骰子点数移动相应的格子。\n2.每个格子都有任务，也可以自行商量执行其他任务\n3.最先到达终点的人获胜"
});
const roles = ref<any[]>([
	{
		index: 0,
		step: 0,
		nickname: '女生',
		icon: WEBCONFIG.value?.woman,
		end: false,
		style: {
			width: '40px',
			height: '40px',
			left: '0px',
			top: '0px'
		}
	},
	{
		index: 0,
		step: 0,
		nickname: '男生',
		icon: WEBCONFIG.value?.man,
		end: false,
		style: {
			width: '40px',
			height: '40px',
			left: '0px',
			top: '0px'
		}
	}
])
const search = ref({
	vip_id: 0,
	game: 'LOVERS_FLYING_CHESS'
});
const clickAudioContext = createAudio('click');
const beatAudioContext = createAudio('beat');
onLoad((options: any) => {
	$page.title();
    if(options.id==='custom')
    {
        const gameCustom= useGameCustom(search.value.game);
        gameCustom.get().then((data:any)=>{
            list.value = data;
			nextTick(initGame);
        }).catch((err:any)=>{
            uni.showModal({
                title: '提示',
                content: err.msg,
                showCancel: false,
                confirmText: '返回',
                success: (res: any) => {
                    close();
                }
            })
        })
    }else{
        search.value.vip_id = options.id;
		getQuestionList();
    }
})
onUnload(() => {
	beatAudioContext.destroy();
	clickAudioContext.destroy();
})
const getQuestionList = () => {
	$http.get('Question/list', {
		data: search.value
	})
		.then((res: any) => {
			if (res.code === $http.ResponseCode.SUCCESS) {
                game.value.theme=res.data.game.theme
                game.value.bg=res.data.game.bg
                if (res.data.game.rule_content) {
                    game.value.rule_content = res.data.game.rule_content;
                }
				list.value = res.data.list;
				nextTick(initGame);
			} else {
				uni.showModal({
					title: '提示',
					content: res.msg,
					showCancel: false,
					confirmText: '返回',
					success: (res: any) => {
						close();
					}
				})
			}
		}).catch((err: any) => {
		})
}
const initGame = () => {
	const info = uni.getSystemInfoSync();
	const itemSize = 40;
	let windowTop=100;
	// #ifdef MP-WEIXIN
	windowTop=130;
	// #endif
	const offsetWidth=(info.safeArea?.width||info.windowWidth) - 100;
	const offsetHeight=(info.safeArea?.height||info.windowHeight) - windowTop;
	containerStyle.value.height = `${offsetHeight}px`;
	containerStyle.value.width = `${offsetWidth}px`;
	let perimeter = 2 * (offsetWidth + offsetHeight);
	let gap = perimeter / list.value.length;

	for (let i = 0; i < list.value.length; i++) {
		let distance = i * gap;
		let x: number, y: number;

		if (distance < offsetWidth) {
			x = distance - itemSize / 2;
			y = -itemSize / 2;
		} else if (distance < offsetWidth + offsetHeight) {
			x = offsetWidth - itemSize / 2;
			y = distance - offsetWidth - itemSize / 2;
		} else if (distance < 2 * offsetWidth + offsetHeight) {
			x = 2 * offsetWidth + offsetHeight - distance - itemSize / 2;
			y = offsetHeight - itemSize / 2;
		} else {
			x = -itemSize / 2;
			y = perimeter - distance - itemSize / 2;
		}

		list.value[i].style = {
			width: itemSize + 'px',
			height: itemSize + 'px',
			left: x + 'px',
			top: y + 'px',
			'--item-bg-deg': `${(i * 360 / list.value.length).toFixed(0)}deg`
		}
		if (i === 0) {
			roles.value.map((item: any) => {
				item.style = {
					width: itemSize + 'px',
					height: itemSize + 'px',
					left: x + 'px',
					top: y + 'px',
				}
			})
		}
	}
}
let CurrentRoleIndex = 0;
const diceFinish = (step: number) => {
	move(CurrentRoleIndex, step);
	CurrentRoleIndex++;
	if (CurrentRoleIndex >= roles.value.length) {
		CurrentRoleIndex = 0;
	}
}
const move = (roleIndex: number, step: number) => {
	let role = roles.value[roleIndex];
	role.step++;
	let timeEr: number;
	timeEr = setInterval(() => {
		if (step <= 0) {
			clearInterval(timeEr);
			gameOver();
			setSelected(list.value[role.index]);
			return;
		}
		step--;
		role.index++;
		if (role.index >= list.value.length) {
			clearInterval(timeEr);
			gameOver();
			role.index = 0;
			role.end = true;
		}
		moveIncrement(roleIndex, role.index);
	}, 300);
}
const moveIncrement = (roleIndex: number, listIndex: number) => {
	beatAudioContext.restPlay();
	roles.value[roleIndex].style = {
		...roles.value[roleIndex].style,
		...list.value[listIndex].style
	}
}
const taskItem = ref({
	title: '任务',
	content: '',
	icon: '',
})
const setSelected = (item: any) => {
	taskItem.value.title = item.nature_text || '任务';
	let content = item.content;
	// {$role1},{$role2}
	for (let i = 0; i < roles.value.length; i++) {
		const item = roles.value[i];
		content = content.replaceAll('{$role' + (i + 1) + '}', item.nickname);
	}
	taskItem.value.content = content;
	taskItem.value.icon = item.icon;
	showPopup.value = true;
}
const gameOver = () => {
	// 当roles中有end为true时，并且所有人的step一致时，游戏结束
	let end = false;
	let endStep = 0;
	let gameResult = [];
	for (let i = 0; i < roles.value.length; i++) {
		const item = roles.value[i];
		if (item.end) {
			end = true;
			endStep = item.step;
			gameResult.push(item.nickname);
			break;
		}
		if (end && item.step < endStep) {
			end = false;
		}
	}
	if (end) {
		uni.showModal({
			title: '游戏结束',
			content: `恭喜${gameResult.join(',')}获胜`,
			confirmText: '重来',
			cancelText: '结束',
			success: (res: any) => {
				if (res.confirm) {
					reset();
				} else {
					close();
				}
			}
		})
	}
}
const reset = (confirm?: boolean) => {
	if (confirm) {
		uni.showModal({
			title: '提示',
			content: '确定要重来吗？',
			success: (res: any) => {
				if (res.confirm) {
					reset();
				}
			}
		})
		return;
	}
	roles.value.map((item: any) => {
		item.index = 0;
		item.end = false;
		item.step = 0;
		item.style = list.value[0].style;
	})
}
const close = (confirm?: boolean) => {
	if (confirm) {
		uni.showModal({
			title: '提示',
			content: '确定要结束游戏吗？',
			success: (res: any) => {
				if (res.confirm) {
					close();
				}
			}
		})
		return;
	}
    $page.switch('/pages/index/index');
}
const palyClickAudio=()=>{
	clickAudioContext.restPlay();
}
</script>

<style lang="scss" scoped>
.content {
	--content-bg: linear-gradient(180deg, #fdcbf1, #e6dee9);
	--item-bg-1: #df89b5;
	--item-bg-2: #bfd9fe;
	--item-bg-3: #fed6e3;
	--item-bg-4: #a8edea;
	--rule-color: #df89b5;
	height: 100vh;
	width: 100vw;
	display: flex;
	justify-content: center;
	background-image: var(--content-bg);
	background-size: 100% 100%;
	background-repeat: no-repeat;
	overflow: hidden;
	backdrop-filter: blur(10px);
	box-sizing: border-box;
	// #ifdef H5
	align-items: center;
	// #endif
	// #ifdef MP-WEIXIN
	padding-bottom: 80px;
	align-items: flex-end;
	// #endif

	&-page-black {
		--content-bg: linear-gradient(180deg, #0c1014, #121c29);
		--item-bg-1: #27282d;
		--item-bg-2: #2e3035;
		--item-bg-3: #a8b2c1;
		--item-bg-4: #d6d9e2;
		--rule-color: var(--xl-white);
	}

	&-page-purple {
		--content-bg: linear-gradient(180deg, #4a4c92, #363455);
		--item-bg-1: #817fa4;
		--item-bg-2: #918fb3;
		--item-bg-3: #c8c9ef;
		--item-bg-4: #e7e9f8;
		--rule-color: var(--xl-white);
	}

	&-page-cyan {
		--content-bg: linear-gradient(180deg, #022227, #325b5d);
		--item-bg-1: #7a9ba0;
		--item-bg-2: #7d9ea3;
		--item-bg-3: #cbe4e1;
		--item-bg-4: #dae6e4;
		--rule-color: var(--xl-white);
	}

	&-page-silvery {
		--content-bg: linear-gradient(180deg, #acb6bf, #506382);
		--item-bg-1: #c4cbd5;
		--item-bg-2: #a2a8b2;
		--item-bg-3: #b2c1d6;
		--item-bg-4: #dae1e9;
		--rule-color: var(--xl-white);
	}
}

.box-line {
	position: relative;
}

.item {
	--item-bg-deg: 0deg;
	width: 0px;
	height: 0px;
	background-image: linear-gradient(var(--item-bg-deg), var(--item-bg-1) 0, var(--item-bg-2));
	background-color: #FFFFFF;
	color: var(--xl-white);
	font-weight: 600;
	border-radius: 6px;
	position: absolute;
	left: 50%;
	top: 50%;
	transition: all 0.3s ease-in-out;
	display: flex;
	justify-content: center;
	align-items: center;
}

.item:nth-child(odd) {
	background-image: linear-gradient(var(--item-bg-deg), var(--item-bg-3) 0, var(--item-bg-4));
}

.dice-position {
	width: 100px;
	height: 100px;
	position: absolute;
	left: 50%;
	top: 60%;
	transform: translate(-50%, -50%);
	background-color: #FFFFFF;
	border-radius: 30px;
	display: flex;
	justify-content: center;
	align-items: center;
}

.rule-position {
	width: 70%;
	position: absolute;
	left: 50%;
	top: 30%;
	transform: translate(-50%, -50%);
	border-radius: 10px;
	background: linear-gradient(180deg, var(--item-bg-1), var(--item-bg-2));
	padding: 20px;
	color: var(--rule-color);
}
.rule-color{
	color: var(--rule-color);
}
.btn-position {
	width: 70%;
	position: absolute;
	left: 50%;
	bottom: 10%;
	transform: translate(-50%, -50%);
}</style>
